package com.smalls.newvideotwo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.smalls.newvideotwo.R;
import com.smalls.newvideotwo.utils.MeasureUtil;


/**
 * Created by hs on 2018/3/9.
 */

@SuppressLint("AppCompatCustomView")
public class LoadImageView extends ImageView {
    private int width = 0;
    private int height = 0;
    private boolean init = false;
    private boolean isLoad = false;
    public LoadImageView(Context context) {
        super(context);
    }

    public LoadImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public LoadImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (!init) {
            init = true;
            TypedArray a = context.obtainStyledAttributes(attrs,
                    R.styleable.Views);
            width = a.getLayoutDimension(R.styleable.Views_android_layout_width, 0);
            height = a.getLayoutDimension(R.styleable.Views_android_layout_height, 0);
            a.recycle();
            width = (int) MeasureUtil.getWidthSize(width);
            height = (int) MeasureUtil.getHeightSize(height);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (!isLoad) {
            isLoad = true;
            ViewGroup.LayoutParams params = getLayoutParams();
            if (params != null && params instanceof ViewGroup.MarginLayoutParams) {
                fillLayoutParams((ViewGroup.MarginLayoutParams) params);
                if (width > 0) {
                    params.width = width;
                }
                if (height > 0) {
                    params.height = height;
                }
            }
            setLayoutParams(params);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void fillLayoutParams(ViewGroup.MarginLayoutParams params) {
        params.bottomMargin = (int) MeasureUtil
                .getHeightSize(params.bottomMargin);
        params.topMargin = (int) MeasureUtil.getHeightSize(params.topMargin);
        params.leftMargin = (int) MeasureUtil.getWidthSize(params.leftMargin);
        params.rightMargin = (int) MeasureUtil.getWidthSize(params.rightMargin);
    }
}
